<!--
 * @Author: hua
 * @Date: 2020-07-21 14:20:36
 * @description: 
 * @LastEditors: hua
 * @LastEditTime: 2020-09-30 15:13:47
--> 
<template>
  <div
    style="width:100%;height:50px;line-height:50px;display:flex;flex-direction:row;justify-content:space-between"
  >
    <div style="width:50%;display:flex;flex-direction:row;">
      <div style="font-weight:bold;">{{$t("bindEquipment")}}</div>
      <el-link
        @click.native="goBehindCodeTable"
        style="line-height:30px;height:30px;margin-top:12px;margin-left:30px;font-size: 14px;font-family: Helvetica Neue;font-weight: 500;line-height: 19px;color: #4E9AFF;opacity: 1;"
        type="info"
        :underline="true"
      >{{$t("WatchBindedEquipment")}}</el-link>
    </div>
    <div style="width:50%;display:flex;flex-direction:row;justify-content:flex-end">
      <!-- COM -->
      <el-select
        size="mini"
        :placeholder="$t('ChooseCom')"
        style="height:30px;line-height:30px;margin-top:12px;width:100px;"
        v-model="com"
      >
        <el-option
          v-for="(item,index) in portList"
          :key="index"
          :label="item.comName"
          :value="item.comName"
        ></el-option>
      </el-select>
      <el-button
        :loading="fullscreenLoading"
        size="mini"
        type="primary"
        style="height:29px;margin-top:13px;margin-left:12px;background: #2ADA93;"
        @click="connect(com)"
      >{{$t("Connect")}}</el-button>
      <!-- <el-button
        size="mini"
        type="primary"
        style="height:30px;margin-top:11px;margin-left:12px"
        @click="send"
      >{{$t("Send")}}</el-button> -->
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { Message, Loading } from "element-ui";
export default {
  name: "HeaderBindEquipment",
  data() {
    return {
      com: "",
      portList: [],
      imei: "",
      fullscreenLoading: false,
    };
  },
  computed: {
    ...mapGetters(["userInfo"]),
  },
  created() {
    /* setTimeout(() => {
      window.bindInfo.imei = "862061043562718";
    }, 3000); */
    let rel = serialport.list();
    rel.then(
      (ports) => {
        console.log("成功，串口列表为data:", ports);
        this.portList = ports;
        if (window.localStorage.getItem("com")) {
          window.comName = window.localStorage.getItem("com");
          this.com = window.localStorage.getItem("com");
        }
      },
      (error) => {
        console.log("失败err:", error);
      }
    );
    //存在就直接连接
    if (window.localStorage.getItem("com") && !window.firstContentLock) {
      window.comName = window.localStorage.getItem("com");
      window.firstContentLock = true;
      this.connect(window.comName);
    }
  },
  methods: {
    goBehindCodeTable() {
      this.$router.push({ name: "behindCodeTable" });
    },
    send() {
      port.write("{stl_imei}");
      console.log("发送命令：", "{stl_imei}");
    },
    bindOpen() {
      port = new serialport(comName, {
        baudRate: parseInt(115200),
        dataBits: 8, //数据位
        parity: "none", //奇偶校验
        stopBits: 1, //停止位
        flowControl: false,
      });
      //监听打开数据
      port.on("open", (data) => {
        //alert("串口已连接");
        console.log(window.globalLoading);
        this.fullscreenLoading = false;
        Message({
          message: "串口已连接",
          type: "success",
          duration: 5 * 1000,
        });
        setTimeout(() => {
          port.write("{stl_imei}");
          console.log("发送命令：", "{stl_imei}");
        }, 1000);
      });
      port.on("error", (data) => {
        setInterval(() => {
          this.fullscreenLoading = false;
        }, 5000);
        console.log(data.toString());
        if (data.toString().indexOf("Port") == -1) {
          //alert(data);
          Message({
            message: data,
            type: "error",
            duration: 5 * 1000,
          });
        }
      });
      port.on("close", (data) => {
        setInterval(() => {
          this.fullscreenLoading = false;
        }, 5000);

        console.log(data);
        if (!data) {
          return;
        }
        if (
          data
            .toString()
            .indexOf(
              "Reading from COM port (ReadIOCompletion): Operation aborted"
            ) !== -1
        ) {
          window.bindInfo.imei = "";
        }
      });
      //监听返回数据
      port.on("data", (data) => {
        //收hex
        //console.log("recv: " + data.toString("hex"));

        //that.outputValue = `<p>${data.toString()}</p>` + that.outputValue;
        console.log("recv: " + data);
        let str = data.toString();
        //首先先要解析出大括号
        if (str.indexOf("{") !== -1 || str.indexOf("}") !== -1) {
          msg = msg + data.toString();
        }
        //862061043562718
        var array = msg.match(/{(.*?)}/g);
        if (array) {
          msg = "";
          console.log(array[0]);
          let imeiList = array[0].split(":");
          window.bindInfo.imei = imeiList[1].substring(
            0,
            imeiList[1].length - 1
          );
          console.log(window.bindInfo.imei);
        }
        console.log(msg);
        console.log(array);
      });
    },

    connect(comName) {
      this.fullscreenLoading = true;
      let that = this;
      let lock = false;
      window.localStorage.setItem("com", comName);
      if (port) {
        port.close();
        setTimeout(() => {
          this.bindOpen();
        }, 2000);
      } else {
        this.bindOpen();
      }
    },
  },
};
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
</style>
